package com.demo.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.InputStream;
import java.util.List;

/**
 * author:王蒙蒙
 * date创建日期:2025/7/28
 * 类注释说明:
 **/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.InputStream;

public class YamlUtils {


    private static final Logger log = LogManager.getLogger(YamlUtils.class);
    private static final ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());

    /**
     * 读取YAML文件并转换为对象
     */
    public static <T> T loadYaml(InputStream inputStream, Class<T> valueType) {
        try {
            return yamlReader.readValue(inputStream, valueType);
        } catch (Exception e) {
            log.error("读取YAML文件失败", e);
            throw new RuntimeException("读取YAML文件失败", e);
        }
    }

    /**
     * 读取YAML文件并转换为List
     */
    public static <T> List<T> loadYamlList(InputStream inputStream, Class<T> elementType) {
        try {
            // 使用Jackson的类型工厂创建集合类型
            return yamlReader.readValue(inputStream,
                    yamlReader.getTypeFactory().constructCollectionType(List.class, elementType));
        } catch (Exception e) {
            log.error("读取YAML列表文件失败", e);
            throw new RuntimeException("读取YAML列表文件失败", e);
        }
    }

    /**
     * 从classpath加载YAML文件
     */
    public static <T> T loadYamlFromClasspath(String filePath, Class<T> valueType) {
        try (InputStream inputStream = YamlUtils.class.getClassLoader().getResourceAsStream(filePath)) {
            if (inputStream == null) {
                throw new RuntimeException("找不到YAML文件: " + filePath);
            }
            return loadYaml(inputStream, valueType);
        } catch (Exception e) {
            log.error("从classpath加载YAML文件失败: " + filePath, e);
            throw new RuntimeException("从classpath加载YAML文件失败", e);
        }
    }

    /**
     * 从classpath加载YAML列表文件
     */
    public static <T> List<T> loadYamlListFromClasspath(String filePath, Class<T> elementType) {
        try (InputStream inputStream = YamlUtils.class.getClassLoader().getResourceAsStream(filePath)) {
            if (inputStream == null) {
                throw new RuntimeException("找不到YAML文件: " + filePath);
            }
            return loadYamlList(inputStream, elementType);
        } catch (Exception e) {
            log.error("从classpath加载YAML列表文件失败: " + filePath, e);
            throw new RuntimeException("从classpath加载YAML列表文件失败", e);
        }
    }

}

